package com.wangshidai.t3;

import com.wangshidai.t2.HttpMessageUtil;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器 处理N个客户端的上线请求
 */
public class ServerDemo {
    static int count=0;
    Socket socket=null;

    public ServerDemo() {
        try {
            ServerSocket serverSocket =new ServerSocket(9999);
            System.out.println("服务器启动OK");
            while (true){
                socket = serverSocket.accept();
                count++;
                System.out.println("目前"+count+"人上线了");
                //启动一个线程(服务员专门来处理和该客户端的业务逻辑)
                ServerThread thread=new ServerThread();
                thread.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
            ServerDemo demo=new ServerDemo();
    }

    //线程类(服务员)  读取客户端的消息并打印
    class ServerThread extends  Thread{ //内部类 不想让其他类访问，只为所在的外部类服务  内部类可以访问外部类的一切

        @Override
        public void run() {
            while (true){
                String message = HttpMessageUtil.readMessage(socket);
                if (message!=null&&!message.equals("")){
                    System.out.println("第"+count+"个客户端说："+message);
                }

            }


        }
    }

}
